from collections import OrderedDict

from rest_framework.fields import SkipField
from rest_framework.relations import PKOnlyObject


class HookSerializer:
    def to_representation(self, instance):
        ret = OrderedDict()
        fields = self._readable_fields

        for field in fields:
            ####################################
            # 判断当前序列化类中是否有nb_字段名开头的钩子函数（规则自定义）
            if hasattr(self, "change_%s" % field.field_name):
                # 执行钩子方法
                value = getattr(self, "change_%s" % field.field_name)(instance)
                # 该字段的序列化内容被钩子函数返回值覆盖
                ret[field.field_name] = value
            else:
                # 其余逻辑不变，没有钩子和之前一致
                try:
                    attribute = field.get_attribute(instance)
                except SkipField:
                    continue
                check_for_none = attribute.pk if isinstance(attribute, PKOnlyObject) else attribute
                if check_for_none is None:
                    ret[field.field_name] = None
                else:
                    ret[field.field_name] = field.to_representation(attribute)

        return ret
